import Vue from 'vue'
import { Toast } from 'vant'
import Clipboard from 'clipboard'

// Json取值
export function VJsonGet(def, obj) {
  try {
    for (var i = 2; i < arguments.length; i++) obj = obj[arguments[i]]
  } catch (e) {
    console.log(e)
  }
  return obj != null ? obj : def
}
// Json赋值
export function VJsonSet(obj) {
  let o = obj
  for (var i = 1; i < arguments.length - 1; i++) {
    if (i === arguments.length - 2) {
      if (arguments[i + 1] != null) Vue.set(o, arguments[i], arguments[i + 1])
      else Vue.delete(o, arguments[i])
    } else {
      if (o[arguments[i]] == null || (typeof o[arguments[i]] !== 'object')) Vue.set(o, arguments[i], {})
      o = o[arguments[i]]
    }
  }
  return obj
}

// promise处理
export function awaitWrapper(promise) {
  return promise.then(data => [null, data]).catch(err => [err, null])
}

// 生成uuid
export function getUuid(length = 16) {
  const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length))
  }
  return str
}

// 复制文本
export function copy(selector, text) {
  const clipboard = new Clipboard(selector, {
    text: function() {
      return text
    }
  })
  clipboard.on('success', (e) => {
    Toast.success('复制成功')
    // 释放内存
    clipboard.destroy()
  })
  clipboard.on('error', (e) => {
    console.log('该浏览器不支持自动复制')
    console.log(e)
    // 不支持复制
    Toast.fail('复制失败')
    // 释放内存
    clipboard.destroy()
  })
}

export function VTrim(s) {
  if (s == null) return null
  s = s + ''
  return s.replace(/(^\s*)|(\s*$)/g, '')
}

// 获得长度（全角长度为2）
export function VLength(s) {
  if (s == null) return 0
  if (typeof s !== 'string') s += ''
  return s.replace(/[^\x00-\xff]/g, '01').length
}

export function VHtml(s) {
  if (s == null) return ''
  s = s + ''
  s = s.replace(/ /g, '&nbsp;')
  return s
}

// Json复制
export function VJsonCopy(obj) {
  try {
    return JSON.parse(JSON.stringify(obj))
  } catch (e) {
    console.log(e)
  }
  return null
}

// Json转化
export function VJsonParse(s) {
  try {
    return JSON.parse(s)
  } catch (e) {
    console.log(e)
  }
  return null
}

// Json查询
export function VJsonFind(object, judge) {
  if (object == null) return null
  for (const key in object) {
    if (judge != null && (typeof judge) === 'function') {
      if (judge(key, object[key], object)) return key
    } else {
      if (object[key] === judge) return key
    }
  }
  return null
}

// 事件的防抖处理
export function debounce(fn, t) {
  const delay = t || 500
  let timer = null
  return function(...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

// 事件的节流处理
export function throttle(fn, t) {
  let timer = null
  const delay = t || 500
  return function(...args) {
    if (timer) {
      return
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

// base64转文件
export function VDataURLtoFile(dataURL, fileName) {
  return new Promise((resolve, reject) => {
    try {
      const arr = dataURL.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      resolve({
        code: 0,

        content: '操作成功',
        data: new File([u8arr], fileName, {
          type: mime
        })
      })
    } catch (error) {
      resolve({
        code: 500,
        content: '操作失败',
        data: error
      })
    }
  })
}
// 文件转Image
export function VFImage(file) {
  return new Promise((resolve, reject) => {
    if (!file || !/image\//.test(file.type)) {
      resolve({
        code: 500,
        content: '文件格式不正确'
      })
    } else {
      var reader = new FileReader()
      reader.onloadend = (e) => {
        resolve({
          code: 0,
          content: '操作成功',
          data: e.target.result
        })
      }
      reader.onerror = () => {
        resolve({
          code: 500,
          content: '文件加载失败'
        })
      }
      reader.readAsDataURL(file)
    }
  })
}

